//
//  ZSGroupTableView.m
//  ZhuShou
//
//  Created by Dejun Liu on 15/10/30.
//  Copyright © 2015年 jw. All rights reserved.
//

#import "ZSGroupTableView.h"

@interface ZSGroupTableView()<UIScrollViewDelegate>

@property (nonatomic,strong) NSMutableArray *viewsArray;

@end

@implementation ZSGroupTableView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _scrollView = [[UIScrollView alloc] initWithFrame:frame];
        [self addSubview:self.scrollView];
        _scrollView.pagingEnabled = YES;
        _scrollView.delegate = self;
        
        self.viewsArray = [NSMutableArray array];
    }
    return self;
}

- (void)addAView:(UIView *)view
{
    [self.viewsArray addObject:view];
    [self.scrollView addSubview:view];
    [self setLayout];
}

- (void)setLayout
{
    self.scrollView.top = 0;
    self.scrollView.width = self.width;
    self.scrollView.height = self.height;
    
    [self.viewsArray enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIView *view = obj;
        view.width = self.scrollView.width;
        view.height = self.scrollView.height;
        view.left = view.width*idx;
        view.top = 0;
    }];
    
    self.scrollView.contentSize = CGSizeMake(self.scrollView.width*self.viewsArray.count, self.scrollView.height);
}

- (void)setShowIndex:(NSInteger)index
{
    [self.scrollView setContentOffset:CGPointMake(self.scrollView.width * index, 0)];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.scrollView) {
        if (self.currentIndexChangeBlock) {
            float offsetX = scrollView.contentOffset.x;
            NSInteger page = floor(offsetX/scrollView.width);
            self.currentIndexChangeBlock(page);
        }
    }
}

@end
